<!-- 
  【小弹窗】列表查询数据区域 
-->
<template>
  <div class="dialogContain">
    <div style="display: flex;border-bottom: 1px solid #000;">
      <div style="display:flex">
        <!-- 用于选单的提交事件触发 -->
        <el-button
          type="primary"
          size="mini"
          style="margin-bottom:5px"
          v-if="operateType == 'selectOrder'"
          @click="createOrderClick"
        >提 交</el-button>
        <el-button
          v-else
          type="primary"
          size="mini"
          style="margin-bottom: 5px"
          @click="returnData"
        >返回数据</el-button>
        <div v-if="openType == 'typeManage'" style="margin-left:10px">
          <el-button
            type="success"
            size="mini"
            style="margin-bottom: 5px"
            @click="creatDateClick"
          >创建数据</el-button>
          <el-button type="info" size="mini" style="margin-bottom: 5px" @click="editDataClick">修改数据</el-button>
        </div>
      </div>
      <div style="display: flex; margin-bottom: 5px" v-if="operateType == 'selectMany'">
        <div style="display: flex; flex-shrink: 0; align-items: center">当前多选值：</div>
        <div style="display: flex; align-items: center; overflow: auto">
          <el-tag
            v-for="(item, index) in selectTableData"
            :key="item.id"
            closable
            size="mini"
            style="margin-left: 10px"
            @close="handleClose(item, index)"
          >{{ item.name }}</el-tag>
        </div>
      </div>
    </div>
    <!-- 筛选方案区域 -->
    <div class="searchBoxClass">
      <div v-if="openType == 'typeManage'">
        名称 / 编码：
        <el-input size="mini" v-model="typeManageValue"></el-input>
        <!-- 搜索 -->
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          circle
          style="margin-left:10px"
          @click="getTypeManageSelect"
        ></el-button>
      </div>
      <my-progra
        v-else
        :filterProject="filterProject"
        :filterParam="filterParam"
        :paramList="filterParamList"
        :isShow="isShow"
        :menuKey="menuKey"
        @getActionSelect="getActionSelect"
      ></my-progra>
    </div>
    <!-- table表格区域 -->
    <div :class="nameM">
      <table-info
        :nameM="nameM"
        :tableData="tableData"
        :tableHeader="tableHeader"
        :operateType="operateType"
        @selectTdClick="selectTdClick"
        @rowDblclick="rowDblclick"
        @rowClick="rowClick"
        ref="tableChild"
        :maxHeight="maxHeight"
      ></table-info>
    </div>
    <!-- 页码区 -->
    <el-pagination
      v-if="openType != 'typeManage'"
      :page-sizes="[10, 20, 50, 100, 200, 500]"
      :page-size="pagingParam.pageSize"
      :current-page="pagingParam.pageIndex"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagingParam.pageCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <!-- typeMange对话框 -->
    <el-dialog
      :title="titleDialog"
      el-dialog
      center
      v-dialogDrag
      :visible.sync="openDialogVisible"
      :append-to-body="true"
      width="70%"
      :before-close="openDialogClose"
      v-if="openDialogVisible"
    >
      <div>
        <el-button type="primary" size="mini" @click="sumbitTypeManageClick">保存</el-button>
        <div>
          <input-basic ref="inputRef" :formParam="formParam" :rowIndex="0" :editRules="editRules"></input-basic>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MyProgra from "../myProgra.vue"; // 筛选方案
import TableInfo from "../tableInfo.vue";
import InputBasic from "../input/inputBasic.vue";

export default {
  data() {
    return {
      nameM: "xxx_" + Math.ceil(Math.random() * 10),
      filterProject: [], // 筛选 我的方案
      filterParam: [], // 快速筛选的数据
      filterParamList: [],
      //table表格数据
      tableHeader: [], //表头数据
      tableData: [], //表body数据
      openType: "", // 标识弹窗的类型
      submitUrl: "",
      maxHeight: 300,
      menuKey: "",
      isShow: null,
      projectCpn: {},
      pagingParam: {
        pageCount: 10, //总数据量
        pageIndex: 1, //当前查询页
        pageNum: 1, //总页数
        pageSize: 10 //每页返回行数
      }, //页码数据对象
      orgData: null,
      selectTrData: {}, //选中的表格行数据
      selectParamData: {}, // 按对象形式存放选择框选中的数据
      selectTableData: [], //选择框选中的数据

      // typeManage 类型的弹窗（可新增/修改）
      typeManageValue: "",
      addUrl: "",
      editUrl: "",
      titleDialog: "",
      typeManageSubmitUrl: "",
      formParam: {
        params: {}
      },
      editRules: {},
      newDataId: "",
      openDialogVisible: false
    };
  },
  components: {
    MyProgra,
    TableInfo,
    InputBasic
  },
  props: {
    dataId: {
      type: Number,
      default: () => {
        return null;
      }
    },
    actionObj: {
      type: Object,
      default: () => {
        return {};
      }
    },
    operateType: {
      type: String,
      default: () => {
        return "";
      }
    },
    paramValue: {
      type: String,
      default: () => {
        return "";
      }
    },
    unActionValue: {
      type: String,
      default: () => {
        return "";
      }
    },
    autoCreateUrl: {
      type: String,
      default: () => {
        return "";
      }
    },
    selectType: {
      type: String,
      default: () => {
        return "";
      }
    }
  },
  watch: {
    actionObj: {
      handler(nav) {
        // console.log(nav);
        var verify = false; //看板点击弹出窗口判断
        if(nav != null && nav.submitUrl.includes("board")){
          verify =true;
        }
        if (nav != null) {
          this.tableHeader = nav.tableParam;
          this.filterParam = nav.filterParam;
          this.openType = nav.openType;
          this.menuKey = nav.dataKey;
          this.submitUrl = nav.submitUrl;
          this.tableData = [];
          if (this.openType == "typeManage") {
            this.addUrl = nav.addUrl;
            this.editUrl = nav.editUrl;
            this.getTypeManageSelect();
          } else {
            if (
              this.unActionValue == undefined ||
              this.unActionValue == null ||
              this.unActionValue == "" ||
              this.paramValue == undefined ||
              this.paramValue == null ||
              this.paramValue == "" 
            ) {
              if(verify){ //看板点击弹出窗口判断
                if(nav.filterParamList.length > 0){
                  this.filterParamList = nav.filterParamList;
                }else{
                  this.filterParamList = nav.filterParamList[0];
                }
                this.getActionSelect(1, this.filterParamList, 0);
                // console.log(this.filterParamList);
              }else{
                this.getActionSelect(1, [], 0); //进入界面的时候无条件查询
              }
            } else {
              // 进入有条件查询
                  this.filterParamList = [
                    {
                      paramName: this.unActionValue,
                      where: "equal",
                      value: this.paramValue,
                      menuKey: this.menuKey
                    }
                  ];
              this.getActionSelect(1, this.filterParamList, 0);
              // console.log(this.filterParamList);
            }
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.orgData = JSON.parse(sessionStorage.getItem("orgData"));
    this.isShow = 0;
  },
  mounted() {
    // this.getActionSelect(1, [], 1); //进入界面的时候无条件查询
  },
  methods: {
    // 监听 改变一页显示多少行数据
    handleSizeChange(newSize) {
      this.pagingParam.pageSize = newSize;
      this.getActionSelect(
        this.projectCpn.v,
        this.projectCpn.paramsList,
        this.projectCpn.selectProgject
      );
      this.$refs.tableChild.toScrollTop();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.pagingParam.pageIndex = newPage;
      this.getActionSelect(
        this.projectCpn.v,
        this.projectCpn.paramsList,
        this.projectCpn.selectProgject
      );
      this.$refs.tableChild.toScrollTop();
    },
    // 查询数据
    async getActionSelect(v, paramsList, selectProgject) {
      console.log(paramsList);

      this.orgData = JSON.parse(sessionStorage.getItem("orgData"));
      this.projectCpn = {
        v,
        paramsList,
        selectProgject
      };
      this.searchData = {
        pageIndex: this.pagingParam.pageIndex, // 分页
        pageSize: this.pagingParam.pageSize,
        filterParam: paramsList, // 查询的字段条件
        orderParam: [] // 排序
      };
      let paramsData = null;
      if (this.menuKey == "SelectCraftRoute") {
        paramsData = {
          dataId: this.dataId,
          orgId: this.orgData.orgType,
          dataKey: this.menuKey,
          searchData: JSON.stringify(this.searchData)
        };
      } else {
        paramsData = {
          orgId: this.orgData.orgType,
          dataKey: this.menuKey,
          searchData: JSON.stringify(this.searchData)
        };
      }

      let { data: res } = await this.$http.post(
        "/api" + this.submitUrl,
        paramsData
      );
      console.log(paramsData);
      if (res.result) {
        this.tableData = res.obj.items;
        this.pagingParam.pageCount = res.obj.pageCount;
        this.pagingParam.pageIndex = res.obj.pageIndex;
        this.pagingParam.pageNum = res.obj.pageNum;
        this.pagingParam.pageSize = res.obj.pageSize;
        // this.selectRowList = [];
        this.selectTrData = [];
      } else {
        this.$message.error(res.msg);
      }
    },
    // 弹窗类型为 typeManage类型的 查询数据
    async getTypeManageSelect() {
      this.orgData = JSON.parse(sessionStorage.getItem("orgData"));
      let { data: res } = await this.$http.get(
        "/api" + this.submitUrl + this.typeManageValue,
        { params: { orgId: this.orgData.orgType } }
      );
      // console.log(res);
      if (res.result) {
        this.tableData = res.obj.items;
        this.selectTrData = [];
      } else {
        this.$message.error(res.msg);
      }
    },
    // 新建数据
    async creatDateClick() {
      let { data: res } = await this.$http.get("/api" + this.addUrl, {
        params: { orgId: this.orgData.orgType }
      });
      if (res.result) {
        this.titleDialog = res.obj.menuName;
        this.typeManageSubmitUrl = res.obj.submitUrl;
        this.newDataId = res.obj.dataId;
        this.formParam.params = res.formParam;
        this.openDialogVisible = true;
        this.formParam.params.forEach(e => {
          let key = JSON.parse(JSON.stringify(e.paramName));
          if (!e.null) {
            this.editRules[key] = [
              {
                required: true,
                message: "必填项！",
                trigger: "blur"
              }
            ];
          } else {
            this.editRules[key] = [];
          }
        });
      } else {
        this.$message.error(res.msg);
      }
    },

    openDialogClose() {
      this.openDialogVisible = false;
    },
    // 编辑数据
    async editDataClick() {
      console.log(this.selectTrData);
      if (Object.keys(this.selectTrData).length == 0) {
        this.$message.error("请单选行数据");
      } else {
        let { data: res } = await this.$http.get(
          "/api" + this.editUrl + this.selectTrData.id,
          { params: { orgId: this.orgData.orgType } }
        );
        if (res.result) {
          this.titleDialog = res.obj.menuName;
          this.typeManageSubmitUrl = res.obj.submitUrl;
          this.newDataId = res.obj.dataId;
          this.formParam.params = res.formParam;
          this.openDialogVisible = true;
          this.formParam.params.forEach(e => {
            let key = JSON.parse(JSON.stringify(e.paramName));
            if (!e.null) {
              this.editRules[key] = [
                {
                  required: true,
                  message: "必填项！",
                  trigger: "blur"
                }
              ];
            } else {
              this.editRules[key] = [];
            }
          });
        } else {
          this.$message.error(res.msg);
        }
      }
    },
    rowClick(row) {
      this.selectTrData = JSON.parse(JSON.stringify(row));
    },
    // 双击的时候,获取行数据，并立即执行数据
    rowDblclick(row) {
      this.selectTrData = JSON.parse(JSON.stringify(row));
      if (this.operateType != "selectMany") {
        if (this.operateType == "selectOrder") {
          this.createOrderClick();
        } 
        else if(this.operateType == "edit") {
          this.rowDblclickBoard(row);
        } 
        else {
          this.returnData();
        }
      }
    },
    rowDblclickBoard(row) {
      console.log(this.paramsData);
      let params = {
        openType: this.openType, //用于打开页面
        rowId: row.id,
        name:"看板显示",
        url: this.editUrl
      };
      this.$store.commit("eidtActionPath", JSON.parse(JSON.stringify(params)));
      this.$store.commit("pushTabPathList", this.$store.state.activePath);
    },
    //选择框选中的数据
    selectTdClick(rowList) {
      this.selectTableData = rowList;
      this.selectParamData = {};
      rowList.forEach(item => {
        for (let k in item) {
          if (this.selectParamData[k] == undefined) {
            this.selectParamData[k] = [];
            this.selectParamData[k].push(item[k]);
          } else {
            this.selectParamData[k].push(item[k]);
          }
        }
      });
    },
    //去除选中的数据
    handleClose(item, index) {
      // 修改存放的对象
      for (let k in this.selectParamData) {
        this.selectParamData[k].splice(index, 1);
      }
      // 删除对应的选中数据
      this.selectTableData.splice(this.selectTableData.indexOf(item), 1);
      //  取消table的选中状态
      this.$refs.tableChild.$refs.table.toggleRowSelection(item, false);
    },

    //返回数据
    returnData() {
      //多选带出数据
      if (this.operateType == "selectMany") {
        if (Object.keys(this.selectParamData).length == 0) {
          this.$message.error("请勾选需要返回的数据~");
        } else {
          let param = {};
          for (let k in this.selectParamData) {
            this.selectParamData[k].forEach(item => {
              if (param[k] == undefined) {
                param[k] = item + "";
              } else {
                param[k] = param[k] + "," + item;
              }
            });
          }
          this.$emit("returnData", param);
          this.selectTableData = [];
          this.selectParamData = {};
          this.$refs.tableChild.$refs.table.clearSelection();
        }
      }
      // 单选带出数据
      else {
        if (Object.keys(this.selectTrData).length == 0) {
          this.$message.error("请选择需要返回的数据~");
        } else {
          this.$emit("returnData", this.selectTrData);
          console.log(this.selectTrData);
        }
      }
    },

    // 提交【选单】
    createOrderClick() {
      if (Object.keys(this.selectTrData).length == 0) {
        this.$message.error("请选择需要执行的行数据~");
      } else {
        let id = "";
        if (this.selectType == "select") {
          id = this.selectTrData.id;
        } else {
          id = this.selectTrData.detailId;
        }
        this.$confirm("即将提交-行选单", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            let { data: res } = await this.$http.get(
              "/api/" + this.autoCreateUrl + id,
              {
                params: {
                  orgId: this.orgData.orgType
                }
              }
            );
            // console.log(res);
            if (res.result) {
              this.$emit("createOrder", res.openUrl);
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch(() => {});
      }
    },

    // 保存 typeManage 的数据
    async sumbitTypeManageClick() {
      this.$refs.inputRef.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        let roleData = { id: this.newDataId };
        this.formParam.params.forEach(item1 => {
          let key = "";
          if (item1.type == "select") {
            key = JSON.parse(JSON.stringify(item1.actionValue));
            roleData[key] = parseInt(JSON.parse(JSON.stringify(item1.value)));
          } else if (item1.type == "radio" || item1.type == "int") {
            key = JSON.parse(JSON.stringify(item1.paramName));
            roleData[key] = parseInt(JSON.parse(JSON.stringify(item1.value)));
          } else if (item1.type == "float") {
            key = JSON.parse(JSON.stringify(item1.paramName));
            roleData[key] = parseFloat(JSON.parse(JSON.stringify(item1.value)));
          } else {
            key = JSON.parse(JSON.stringify(item1.paramName));
            if (item1.value == null) {
              roleData[key] = "";
            } else {
              roleData[key] = JSON.parse(JSON.stringify(item1.value));
            }
          }
        });
        // console.log(roleData);
        let { data: res } = await this.$http.post(
          "/api" + this.typeManageSubmitUrl,
          roleData
        );
        if (res.result) {
          this.$message.success(res.msg);
          this.getTypeManageSelect();
          this.openDialogVisible = false;
        } else {
          this.$message.error(res.msg);
        }
      });
    }
  }
};
</script>
<style scoped>
.dialogContain {
  width: 100%;
  height: 100%;
}

.select {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
}

.select .onediv {
  font-size: 14px;
  box-sizing: border-box;
  padding: 3px 14px;
  margin: 0 10px;
}

.inputSelect {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.inputSelect .iconselect,
.conditionClass {
  width: 30px;
  height: 23px;
  border-radius: 3px;
  text-align: center;
  line-height: 23px;
  color: #fff;
  background-color: #3a81ff;
  margin-left: 8px;
}

.conditionClass {
  margin-left: 0;
  background-color: #24c024;
}

.inputSelect .funBtn {
  height: 23px;
  margin-left: 8px;
  color: blue;
}

.funBtn:hover {
  color: #d63f3f;
}

.searchBoxClass {
  padding: 5px;
  box-sizing: border-box;
}

.searchBoxClass .el-input {
  width: 180px;
}
</style>